<?php


namespace app\common\model;

use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\Exception;
use think\Db;

// use \app\api\model\User;
use think\Model;

class Order extends Model
{


    /*
     * 订单列表
     * */
    public function orderInfo($data_array)
    {
        $url = config('fastadmin.api_url');
        $page = $data_array['page'] ? $data_array['page'] : 1;
        $where = [];
        if (empty($data_array['type'])) {
            $where['o.status'] = ['>', 0];
        } elseif ($data_array['type'] != 7) {
            $where['o.status'] = ['=', $data_array['type']];
        } elseif ($data_array['type'] == 7) {
            $where['o.status'] = ['in', '4,5,6'];
        }
        $filed = ['o.id as order_id,o.status,o.money,o.num,o.item,o.order_time,g.image,g.name,o.type,o.create_time,o.title,o.address_id,o.goods_id,o.pid'];
        // $data_array['user_id'] = 135;
        $order = Db::name('order')
            ->alias('o')
            ->join('goods g', 'o.goods_id = g.id')
            ->where($where)
            ->field($filed)
            ->where('user_id', $data_array['user_id'])
            ->order('create_time desc')
            ->page($page, 10)
            ->select();

        if ($order) {
            foreach ($order as &$val) {
                $val['image'] = $url . $val['image'];
                $val['order_time'] = date("Y-m-d H:i", $val['order_time']);
                $val['item'] = json_decode($val['item'], true);
                if ($val['pid'] > 1) {
                    $val['money'] = $val['money'] * $val['num'];
                }
            }
        }

        return $order;
    }


    /*
     * 详情
     * */
    public function details($data_array)
    {
        $url = config('fastadmin.api_url');
        $data = Db::name('order')->where('id', $data_array['order_id'])->field('user_id,order_id,username,number,create_time', true)->order('order_time desc')->find();
        $data['item'] = json_decode($data['item'], true);
        $data['order_time'] = date('Y-m-d H:i', $data['order_time']);
        $address = Db::name('user_address')->where('id', $data['address_id'])->field('create_time,update_time', true)->find();
        $title = Db::name('coupons')->where('id', $data['cou_id'])->value('title');
        $goods = Db::name('goods')->where('id', $data['goods_id'])->field('name,image,item')->find();

        $item = json_decode($goods['item'], true);

        foreach ($item as $val) {
            if ($val['title'] == $data['title']) {
                if (isset($val['intro'])) {
                    $money = $val['intro'];
                }
                if (isset($val['integral'])) {
                    $money = $val['integral'];
                }

            }
        }
        if ($data['pid'] > 1) {
            $data['price'] = $data['money'] * $data['num'];
        }
        $data['money'] = $data['money'];
        $data['goods_name'] = $goods['name'];
        $data['image'] = $url . $goods['image'];
        $res = ['data' => $data, 'address' => $address, 'title' => $title];
        return $res;
    }


    /*
     * 生成订单
     * */
    public function createOrders($data)
    {
        // 地址id,商品id，数量，备注，优惠券id,支付类型：
        $money = $data['money'] * $data['num'];
        // 生成订单id
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        // 获取用户信息
        $user = Db::name('user')->where('id', $data['user_id'])->field('is_vip,money,nickname,openid')->find();
        if ($data['cou_id']) {
            // 获取用户优惠券信息
            $coupNum = Db::name('user_coupons')->where(['is_del' => 1, 'user_id' => $data['user_id'], 'id' => $data['cou_id']])->find();

            if (!$coupNum) return ['msg' => '暂无优惠券', 'data' => '', 'code' => 0];
            // 判断优惠券
            if ($coupNum['status'] != 1) return ['msg' => '您的优惠券已使用或已过期', 'data' => '', 'code' => 0];
            // 判断满减条件
            $coup = Db::name('coupons')->where('id', $coupNum['cou_id'])->find();

            if ($money < $coup['full']) return ['msg' => '未达到满减条件', 'data' => '', 'code' => 0];
            $money = $money - $coup['reduces'];
        } else {
            $money = $money - 0;
        }
        $number = Db::name('user_address')->where('id', $data['address_id'])->value('phone');

        $user_card = Db::name('user_card')->where(['member_id' => $data['user_id']])->find();
        $is_vip_card = 0;
        if($user_card && $user_card['status'] == 1){
            $is_vip_card = 1;
        }


        $data = [
            'order_id' => $order_id,
            'address_id' => $data['address_id'],
            'goods_id' => $data['goods_id'],
            'name' => $data['name'],// 商品名称
            'title' => $data['norms'],// 规格
            'money' => $money,// 金额
            'num' => $data['num'],// 数量
            'cou_id' => $data['cou_id'],// 优惠券
            'type' => $data['type'],// 支付类型
            'desc' => $data['desc'],// 备注
            'price' => $money,// 总金额
            'number' => $number,// 手机号
            'status' => 1,
            'user_id' => $data['user_id'],// 用户id
            'username' => $user['nickname'],// 用户昵称
            'is_vip' => $is_vip_card,
            'order_time' => time(),// 下单时间
            'create_time' => time(),// 创建时间
        ];


        // 更改规格的库存
        $item = Db::name('goods')->where('id', $data['goods_id'])->value('item');

        $item = json_decode($item, true);

        foreach ($item as $key => &$val) {
            if ($val['title'] == $data['title']) {
                if ($val['stock'] < $data['num']) return ['msg' => '库存不足', 'data' => '', 'code' => 0];
                $item[$key]['stock'] = $val['stock'] - $data['num'];
            }
        }

        // 1：余额支付，2：微信支付
        if ($data['type'] == 1) {
            $consume = ['user_id' => $data['user_id'], 'sub_user_id' => 0, 'type' => 1, 'status' => 2, 'money' => $money, 'content' => '余额购买', 'create_time' => time(), 'state' => 1];
            if ($data['money'] > $user['money']) return ['msg' => '余额不足,请充值', 'data' => '', 'code' => 0];
            Db::startTrans();
            try {
                Db::commit();
                // 生成订单
                $data['status'] = 2;
                Db::name('order')->insert($data);
                Db::name('user_coupons')->where('id', $data['cou_id'])->setDec('num', 1);
                Db::name('user_consume')->insert($consume);
                Db::name('user')->where('id', $data['user_id'])->setDec('money', $money);
                Db::name('goods')->where('id', $data['goods_id'])->update(['item' => json_encode($item)]);
                // 是会员,定期返还完金额，生成记录
//                if ($user['is_vip']) {
//                    if (Db::name('user_refund_amount')->where('user_id', $data['user_id'])->count()) {
//                        Db::name('user_refund_amount')->where('user_id', $data['user_id'])->setInc('money', $money);
//                    } else {
//                        $amount = ['user_id' => $data['user_id'], 'money' => $money, 'refund_amount' => 0, 'create_time' => time()];
//                        Db::name('user_refund_amount')->insert($amount);
//                    }
//                }

                // $data = ['id'=>$data['user_id'],'money'=>$money];
                // $user = new \app\common\model\User();
                // $user::isItem($data);
                return ['msg' => '购买成功', 'data' => '', 'code' => 1];
            } catch (Exception $exception) {
                Db::rollback();
                return ['msg' => '购买失败', 'data' => '', 'code' => 0];
            }


        } else {

            // 调用config
            $config = config('wechat_pay');
            $app = Factory::payment($config);
            Db::name('order')->insert($data);
            $result = $app->order->unify([
                'body' => '充值' . $data['money'] . '元',
                'out_trade_no' => $order_id,
                // 'response_type' => 'array',
                'total_fee' => $money * 100,//测试
                'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/payOrder',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        }

        if ($config) {
            return ['msg' => '调用成功', 'code' => 1, 'data' => $config];
        } else {
            return ['msg' => '调用失败', 'code' => 0, 'data' => $config];
        }

    }


    public function createVipGoodsOrders($data)
    {


        //获取用户是否开通会员卡
        $userVipCard = Db::name('user_card')->where(['member_id' => $data['user_id']])->find();
        if (!$userVipCard) {
            return ['msg' => '您未开通会员卡', 'data' => '', 'code' => 0];
        }

        if ($userVipCard['status'] == 2) {
            return ['msg' => '您的会员卡已过期', 'data' => '', 'code' => 0];
        }

        if ($data['num'] > $userVipCard['nums']) {
            return ['msg' => '您最多可购买' . $userVipCard['nums'] . "件", 'data' => '', 'code' => 0];
        }

        $money = $data['money'] * $data['num'];
        // 生成订单id
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        // 获取用户信息
        $user = Db::name('user')->where('id', $data['user_id'])->field('is_vip,money,nickname,openid')->find();
        $number = Db::name('user_address')->where('id', $data['address_id'])->value('phone');
        $data = [
            'order_id' => $order_id,
            'address_id' => $data['address_id'],
            'goods_id' => $data['goods_id'],
            'name' => $data['name'],// 商品名称
            'title' => $data['norms'],// 规格
            'money' => $money,// 金额
            'num' => $data['num'],// 数量
            'type' => $data['type'],// 支付类型
            'desc' => $data['desc'],// 备注
            'price' => $money,// 总金额
            'number' => $number,// 手机号
            'status' => 1,
            'user_id' => $data['user_id'],// 用户id
            'username' => $user['nickname'],// 用户昵称
            'order_time' => time(),// 下单时间
            'create_time' => time(),// 创建时间
        ];


        // 更改规格的库存
        $item = Db::name('goods')->where('id', $data['goods_id'])->value('item');
        $item = json_decode($item, true);
        foreach ($item as $key => &$val) {
            if ($val['title'] == $data['title']) {
                if ($val['stock'] < $data['num']) return ['msg' => '库存不足', 'data' => '', 'code' => 0];
                $item[$key]['stock'] = $val['stock'] - $data['num'];
            }
        }
        // 生成订单

        // 1：余额支付，2：微信支付
        if ($data['type'] == 1) {
            $data['status'] = 2;
            $consume = ['user_id' => $data['user_id'], 'sub_user_id' => 0, 'type' => 1, 'status' => 2, 'money' => $money, 'content' => '余额购买', 'create_time' => time(), 'state' => 1];
            if ($data['money'] > $user['money']) return ['msg' => '余额不足,请充值', 'data' => '', 'code' => 0];
            Db::startTrans();
            try {
                Db::name('order')->insert($data);
                Db::name('user_consume')->insert($consume);
                Db::name('user')->where('id', $data['user_id'])->setDec('money', $money);
                Db::name('goods')->where('id', $data['goods_id'])->update(['item' => json_encode($item)]);
                Db::name('user_card')->where(['member_id' => $data['user_id'], 'status' => 1])->setDec('nums', $data['num']);
                Db::commit();
                return ['msg' => '购买成功', 'data' => '', 'code' => 1];
            } catch (Exception $exception) {
                Db::rollback();
                return ['msg' => '购买失败', 'data' => '', 'code' => 0];
            }
        } else {
            Db::name('order')->insert($data);
            // 调用config
            $config = config('wechat_pay');
            $app = Factory::payment($config);
            $result = $app->order->unify([
                'body' => '充值' . $data['money'] . '元',
                'out_trade_no' => $order_id,
                // 'response_type' => 'array',
                'total_fee' => $money * 100,//测试
                'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/payVipGoodsOrder',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);
        }

        if ($config) {
            return ['msg' => '调用成功', 'code' => 1, 'data' => $config];
        } else {
            return ['msg' => '调用失败', 'code' => 0, 'data' => $config];
        }

    }


    /*
     * 爱心值兑换商品
     * */
    public function converts($data)
    {
        // 获取商品信息
        $goods = Db::name('goods')->where('id', $data['goods_id'])->find();
        $item = json_decode($goods['item'], true);
        // 获取用户信息
        $user = Db::name('user')->where('id', $data['user_id'])->field('nickname,score')->find();
        if ($item[0]['integral'] * $data['num'] > $user['score']) return ['code' => 0, 'msg' => '爱心值不足,暂不能兑换', 'data' => ''];
        $number = Db::name('user_id')->where('id', $data['address_id'])->value('phone');
        $datas = [
            'order_id' => date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999)),
            'user_id' => $data['user_id'],
            'username' => $user['nickname'],
            'name' => $goods['name'],
            'title' => $data['norms'],
            'address_id' => $data['address_id'],
            'num' => $data['num'],
            'price' => $item[0]['integral'] * $data['num'],
            'money' => $item[0]['integral'] * $data['num'],
            'goods_id' => $data['goods_id'],
            'number' => $number,
            'status' => 2,
            'type' => 3,
            'pay_time' => time(),
            'order_time' => time(),
            'create_time' => time()
        ];
        $good = Db::name('goods')->where('id', $data['goods_id'])->value('item');

        $item = json_decode($good, true);
        foreach ($item as $key => $val) {
            if ($val['title'] == $data['norms']) {
                if ($val['stock'] < $data['num']) return ['msg' => '库存不足', 'data' => '', 'code' => 0];
                $item[$key]['stock'] = $val['stock'] - $data['num'];
            }
        }
        Db::startTrans();
        try {
            $consume = ['user_id' => $data['user_id'], 'sub_user_id' => 0, 'type' => 2, 'status' => 2, 'money' => $data['num'] * $item[0]['integral'], 'content' => '爱心值购买', 'create_time' => time(), 'state' => 1];
            Db::name('order')->insert($datas);
            Db::name('user')->where('id', $data['user_id'])->setDec('score', $item[0]['integral'] * $data['num']);
            Db::name('goods')->where('id', $data['goods_id'])->update(['item' => json_encode($item)]);
            Db::name('user_consume')->insert($consume);
            Db::commit();
            return ['code' => '1', 'msg' => '兑换成功', 'data' => ''];
        } catch (Exception $exception) {
            Db::rollback();
            return ['code' => '0', 'msg' => '兑换失败', 'data' => ''];
        }
    }


    /*
     * 申请退货
     * */
    public function returnGoods($data)
    {
        if (!$data['apply']) return ['code' => 0, 'msg' => '请输入退货理由', 'data' => ''];
        $res = Db::name('order')->where('id', $data['order_id'])->update(['apply' => $data['apply'], 'status' => 4]);
        if ($res) {
            return ['code' => '1', 'msg' => '提交成功', 'data' => ''];
        } else {
            return ['code' => '0', 'msg' => '提交失败', 'data' => ''];
        }

    }


    /*
     * 秒杀商品
     * */
    public function kills($data)
    {
        //连接
        // $redis = new \Redis();
        // $redis->connect('127.0.0.1', 6379);

        $time = time();
        $config = config('wechat_pay');
        $app = Factory::payment($config);

        $money = $data['money'] * $data['num'];
        $goods = Db::name('goods')->where(['id' => $data['goods_id'], 'activity' => 1])->find();
        if (!$goods) return ['code' => '0', 'msg' => '该商品不存在', 'data' => ''];
        if ($goods['end_time'] - $time < 0) return ['code' => '0', 'msg' => '该商品不能秒杀', 'data' => ''];
        if ($data['num'] >= 2) return ['code' => '0', 'msg' => '秒杀商品只能购买一个', 'data' => ''];
        if ($data['cou_id']) {
            // 获取用户优惠券信息
            $coupNum = Db::name('user_coupons')->where(['is_del' => 1, 'user_id' => $data['user_id'], 'id' => $data['cou_id']])->find();
            if (!$coupNum) return ['msg' => '暂无优惠券', 'data' => '', 'code' => 0];
            // 判断优惠券
            if ($coupNum['status'] != 1) return ['msg' => '您的优惠券已使用或已过期', 'data' => '', 'code' => 0];
            // 判断满减条件
            $coup = Db::name('coupons')->where('id', $coupNum['cou_id'])->find();
            if ($money < $coup['full']) return ['msg' => '未达到满减条件', 'data' => '', 'code' => 0];
            $money = $money - $coup['reduces'];
        } else {
            $money = $money - 0;
        }

        $user = Db::name('user')->where('id', $data['user_id'])->field('openid,nickname,money,is_vip')->find();
        $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
        $dataGood = [
            'order_id' => $order_id,
            'user_id' => $data['user_id'],
            'username' => $user['nickname'],
            'name' => $goods['name'],
            'title' => $data['norms'],
            'address_id' => $data['address_id'],
            'num' => $data['num'],
            'goods_id' => $data['goods_id'],
            'money' => $money,
            'price' => $money,
            'type' => $data['type'],
            'cou_id' => $data['cou_id'],
            'status' => 1,
            'desc' => $data['desc'],
            'is_qd' => 1,
            'order_time' => time(),
            'create_time' => time(),
        ];

        $item = Db::name('goods')->where('id', $data['goods_id'])->value('item');
        $item = json_decode($item, true);
        foreach ($item as &$val) {
            if ($val['title'] == $data['norms']) {
                if ($val['stock'] < $data['num']) return ['code' => '0', 'msg' => '库存不足', 'data' => ''];
                $val['stock'] = $val['stock'] - $data['num'];
            }
        }

        $count = Db::name("order")->where(['user_id' => $data['user_id'], 'goods_id' => $data['goods_id'], 'is_qd' => 1])->count();

        if ($count) return ['code' => '0', 'msg' => '已抢过,勿重复抢单', 'data' => ''];

        // key
        // $key = 'list_seckill_goods_id_'.$data['goods_id'];

        // 从链表的头部删除一个元素，返回删除的元素,因为pop操作是原子性，即使很多用户同时到达，也是依次执行
        // $count = $redis->lpop($key);
        // if (!$count) {
        //     return ['msg'=>'已抢光！','data'=>'','code'=>0];
        // }

        //已抢购用户id队列
        // $userListKey = 'user_goods_id_'.$data['goods_id'];

        //判断该用户是否已经抢购过 该用户id是否在抢购用户集合中
        // $userBuyStatus = $redis->sismember($userListKey,$data['user_id']);
        // if($userBuyStatus){
        //     return ['msg'=>'您已抢过！','data'=>'','code'=>0];
        // }

        // 1：余额支付，2：微信支付
        if ($data['type'] == 1) {
            if ($money > $user['money']) return ['msg' => '余额不足,请充值', 'data' => '', 'code' => 0];

            Db::startTrans();
            try {
                // 生成订单
                $dataGood['status'] = 2;
                Db::name('order')->insert($dataGood);
                Db::name('user_coupons')->where(['id' => $data['cou_id'], 'user_id' => $data['user_id']])->setDec('num', 1);
                $item = json_encode($item);
                $consume = ['user_id' => $data['user_id'], 'sub_user_id' => 0, 'type' => 1, 'status' => 2, 'money' => $money, 'content' => '余额购买', 'create_time' => time(), 'state' => 1];
                // 将用户id添加到抢购成功用户集合中
                // $redis->sadd($userListKey,$data['user_id']);
                // $msg = '抢到的人为：'.$user['nickname'];
                // $redis->lpush('success', $msg);
                Db::name('goods')->where('id', $data['goods_id'])->update(['item' => $item]);
                Db::name('user')->where('id', $data['user_id'])->setDec('money', $money);
                Db::name('user_consume')->insert($consume);
                // 是会员,定期返还完金额，生成记录
                if ($user['is_vip']) {
                    if (Db::name('user_refund_amount')->where('user_id', $data['user_id'])->count()) {
                        Db::name('user_refund_amount')->where('user_id', $data['user_id'])->setInc('money', $money);
                    } else {
                        $amount = ['user_id' => $data['user_id'], 'money' => $money, 'refund_amount' => 0, 'create_time' => time()];
                        Db::name('user_refund_amount')->insert($amount);
                    }
                }
                Db::commit();
                return ['msg' => '购买成功', 'data' => '', 'code' => 1];
            } catch (Exception $exception) {
                Db::rollback();
                return ['msg' => '购买失败', 'data' => '', 'code' => 0];
            }
        } else {

            Db::name('order')->insert($dataGood);
            $result = $app->order->unify([
                'body' => '充值' . $data['money'] . '元',
                'out_trade_no' => $order_id,
                // 'response_type' => 'array',
                'total_fee' => $money * 100,//测试
                'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/killOrder',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);

            if ($config) {
                return ['msg' => '成功', 'code' => 1, 'data' => $config];
            } else {
                return ['msg' => '失败', 'code' => 0, 'data' => $config];
            }
        }

    }

    /*
     * 更新订单
     **/
    public function upOrders($data)
    {
        $order = Db::name('order')->where('id', $data['order_id'])->find();
        if (!$order) return ['code' => '0', 'msg' => '该订单不存在', 'data' => ''];
        $user = Db::name('user')->where('id', $data['user_id'])->find();

        $config = config('wechat_pay');
        $app = Factory::payment($config);
        // type: 1: 余额支付
        if ($data['type'] == 1) {
            if ($order['money'] * $order['num'] > $user['money']) return ['msg' => '余额不足,请充值', 'data' => '', 'code' => 0];
            $res = Db::name('order')->where('id', $order['id'])->update(['status' => 2, 'pay_time' => time()]);
            $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');
            $item = json_decode($item, true);
            foreach ($item as &$val) {
                if ($val['title'] == $data['norms']) {
                    if ($val['stock'] < $data['num']) return ['code' => '0', 'msg' => '库存不足', 'data' => ''];
                    $val['stock'] = $val['stock'] - $data['num'];
                }
            }
            // 是会员,定期返还完金额，生成记录
            if ($user['is_vip']) {
                if (Db::name('user_refund_amount')->where('user_id', $data['user_id'])->count()) {
                    Db::name('user_refund_amount')->where('user_id', $data['user_id'])->setInc('money', $order['money'] * $order['num']);
                } else {
                    $amount = ['user_id' => $data['user_id'], 'money' => $order['money'] * $order['num'], 'refund_amount' => 0, 'create_time' => time()];
                    Db::name('user_refund_amount')->insert($amount);
                }
            }
            $item = json_encode($item);
            Db::name('goods')->where('id', $order['goods_id'])->update(['item' => $item]);
            if ($res) {
                return ['code' => 1, 'msg' => '支付成功', 'data' => ''];
            } else {
                return ['code' => 0, 'msg' => '支付失败', 'data' => ''];
            }
        } else {
            $order_id = date('YmdHis', time()) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));

            Db::name('order')->where('id', $data['order_id'])->update(['order_id' => $order_id]);
            $order_id = Db::name('order')->where('id', $data['order_id'])->value('order_id');
            $result = $app->order->unify([
                'body' => '充值' . $data['money'] . '元',
                'out_trade_no' => $order_id,
                // 'response_type' => 'array',
                'total_fee' => $data['money'] * 100,//测试
                'notify_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/api/payCall/upOrders',
                'trade_type' => 'JSAPI',
                'openid' => $user['openid'],
            ]);
            $jssdk = $app->jssdk;
            $config = $jssdk->bridgeConfig($result['prepay_id'], false);

            if ($config) {
                return ['msg' => '成功', 'code' => 1, 'data' => $config];
            } else {
                return ['msg' => '失败', 'code' => 0, 'data' => $config];
            }
        }
    }

    /*
     * 收货成功
     * */
    public function receivings($data)
    {
        $order = Db::name('order')->where('id', $data['order_id'])->find();

        Db::startTrans();
        try {

            // 积分购买返回对等的爱心值
            // if($order['type'] != 3 && $order['status'] == 3)
            if ($order['status'] == 3) {

                // 更改订单状态
                Db::name('order')->where('id', $data['order_id'])->update(['status' => 5, 'logistics_time' => time()]);
//                $money = $order['money'] * $order['num'];
//                $con = ['user_id'=>$data['user_id'],'sub_user_id'=>0,'type'=>2,'status'=>1,'money'=>$money,'content'=>'对等返还的爱心值','create_time'=>time()];
//            }else{
                // 获取商品信息
                $intro = [];
                $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');
                $item = json_decode($item, true);
                foreach ($item as $val) {
                    if ($val['title'] == $order['title']) {
                        $intro[] = $val['integral'];
                    }
                }
                $money = array_sum($intro) * $order['num'];
                // 计算积分，返还积分
                $con = ['user_id' => $data['user_id'], 'sub_user_id' => 0, 'type' => 2, 'status' => 1, 'money' => $money, 'content' => '返还爱心值', 'create_time' => time()];
                // 生成记录
                Db::name('user_consume')->insert($con);
                // 增加爱心值
                Db::name('user')->where('id', $data['user_id'])->setInc('score', $money);
                $money = isset($money) ? $money : $data['money'];
                // 是团长有提成
                $data = ['id' => $order['user_id'], 'money' => $money];
                model('user')::isItem($data);
            }
            // 给上级返利
            model('user')::item($order['user_id'], $order['order_id']);
            Db::commit();
            return ['code' => 1, 'msg' => '收货成功', 'data' => ''];
        } catch (Exception $exception) {
            Db::rollback();
            return ['code' => 2, 'msg' => '收货失败', 'data' => ''];
        }


    }


    /*
     * 物流信息
     * */
    public function logistics($data)
    {
        $order = Db::name('order')->where('id', $data['order_id'])->field('order_time,pay_time,ex_time,logistics_time,address_id')->find();
        $order['order_time'] = date('Y-m-d H:i:s', $order['order_time']);
        $order['pay_time'] = date('Y-m-d H:i:s', $order['pay_time']);
        $order['ex_time'] = date('Y-m-d H:i:s', $order['ex_time']);
        if ($order['logistics_time']) {
            $order['logistics_time'] = date('Y-m-d H:i:s', $order['logistics_time']);
        } else {
            $order['logistics_time'] = "暂未收货";
        }
        $address = Db::name('user_address')->where('id', $order['address_id'])->find();
        $res = ['order' => $order, 'address' => $address];
        return $res;
    }


}